package com.yao.component.pictureselector;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;

import java.util.List;

/**
 * Created by zwj on 2016/1/20.
 */
public class MediaSelector {
    public static final int SELECT_PICTURE=0X001,SELECT_VIDEO=0X002;
    private Context mContext;
    private List<String> selectList;
    private onPictureSelectListener mListener;
    private PictureSelectorReciver reciver;
    private int maxCount=-1;
    private boolean isSingle;
    private int type;
    public MediaSelector(Context context, onPictureSelectListener listener){
        this.mContext=context;
        this.mListener=listener;
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.yao.component.pictureselector.selectimage");
        reciver=new PictureSelectorReciver();
        mContext.registerReceiver(reciver,filter);

    }
    public MediaSelector(Context context, int type, int count, boolean isSingle, onPictureSelectListener listener){
        this.mContext=context;
        this.mListener=listener;
        this.isSingle=isSingle;
        this.type=type;
        if (count>0){
            this.maxCount=count;
        }
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.yao.component.pictureselector.selectimage");
        reciver=new PictureSelectorReciver();
        mContext.registerReceiver(reciver,filter);

    }
    public void show(){
        Intent intent;
        if (type==SELECT_PICTURE){
            intent =new Intent(mContext,PhotoBrowseActivity.class);
        }else if (type==SELECT_VIDEO){
            intent =new Intent(mContext,VideoBrowseActivity.class);
        }else {
            Toast.makeText(mContext,"类型错误",Toast.LENGTH_SHORT).show();
            return;
        }

        intent.putExtra("MAX_COUNT",maxCount);
        intent.putExtra("IS_SINGLE",isSingle);
        mContext.startActivity(intent);
    }
    class PictureSelectorReciver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            selectList=intent.getStringArrayListExtra("select_image");

               if (mListener!=null){
                   if (selectList.size()>0){
                       mListener.onSelect(selectList);
                   }else {
                       mListener.onCancel();
                   }
               }
            if (PhotoBrowseActivity.mSelectedImage!=null){
                PhotoBrowseActivity.mSelectedImage.clear();
            }
            if (VideoBrowseActivity.mSelectedVideo !=null){
                VideoBrowseActivity.mSelectedVideo.clear();
            }
            mContext.unregisterReceiver(reciver);
        }
    }
    public interface onPictureSelectListener{
        public void onSelect(List<String> selectPath);
        public void onCancel();
    }
}
